import { getYMD, getNowFormatDate, getDay, formatGMTDate, sortBy, toPercent } from '../../../../assets/js/util.js'

import echarts from 'echarts'

export default {
    data() {
        return {
            pickerOptions0: {
                disabledDate(time) {
                    return time.getTime() > Date.now() - 8.64e7;
                }
            },
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: '',
                uid: ''
            },
            loading: false,
            searchable: false,
            prop: '',
            order: '',
            title: '职业分析',
            xlsxTitle: '',
            ruleForm: {
                sday: '',
                eday: '',
                startDate: ''
            },
            tableHead1: [],
            tableHead2: [],
            tableData1H: [],
            tableData1: [],
            tableData2H: [],
            tableData2All: [],
            tableData2: [],
            /*当前页显示数量*/
            page1: {
                pageSize: 10,
                pageSizes: [10, 20, 50, 100],
                dataTotal: 0,
                currentPage: 1,
            },
            page2: {
                pageSize: 10,
                pageSizes: [10, 20, 50, 100],
                dataTotal: 0,
                currentPage: 1,
            },
            // 图表数据
            real: {}
        }
    },
    computed: {
        // xlsx() {
        //     return this.title + '.xlsx'
        // }
    },
    methods: {
        dateChange(val) {
            if (val) {
                var val = val.split(" ");
                this.sday = val[0];
                this.eday = val[2];
            }
        },
        // 表格下载
        excel(tableIndex, sheet) {
            this.xlsxTitle = sheet + "-" + this.sday + "到" + this.eday;
            this.downloadExl(this["tableHead" + tableIndex], this["tableData" + tableIndex], this.xlsxTitle, sheet);
        },
        agentChange() {

        },
        attrChange() {

        },
        channelChange() {

        },
        settlWayChange() {

        },
        adPlaceChange() {

        },
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
        },
        search() {
            this.loads();
            this.apiAjax(this.sday, this.eday)
        },
        handleSizeChange2(val) {
            this.page2.pageSize = val;
            this.tableData2 = this.tableData2All.slice((this.page2.currentPage - 1) * (this.page2.pageSize), this.page2.currentPage * this.page2.pageSize);
        },
        handleCurrentChange2(val) {
            this.page2.currentPage = val;
            this.tableData2 = this.tableData2All.slice((this.page2.currentPage - 1) * (this.page2.pageSize), this.page2.currentPage * this.page2.pageSize);
        },
        edit() {

        },
        handleDelete() {

        },
        // arrTojs
        getArrJson(arr) {
            var arrNew = [];
            for (var i = 0; i < arr.length; i++) {
                var obj = {};
                obj.prop = String(i + 2);
                obj.label = arr[i];
                arrNew.push(obj);
            }
            return arrNew;
        },
        // arrTojs
        getArrJson2(arr) {
            var arrNew = [];
            for (var i = 0; i < arr.length; i++) {
                var obj = {};
                obj.prop = String(i);
                obj.label = arr[i];
                arrNew.push(obj);
            }
            return arrNew;
        },
        findData(data) {
            this.sday = formatGMTDate(new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 8), true, true);
            this.eday = formatGMTDate(new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 1), true, true);
            this.ruleForm.startDate = [this.sday, this.eday];
            this.loads();
            this.apiAjax(this.sday, this.eday)
        },
        // 将对象变成数组获取到value 变成数组
        /**
         * 将对象的value 提取出来return返回
         * @author YS
         * @param {*} obj 传入的对象
         */
        returnValueList(obj) {
            var arr = [];
            for (var i in obj) {
                arr.push(obj[i])
            }
            return arr;
        },
        /**
         * 将对象的key 提取出来return返回
         * @author YS
         * @param {*} obj 传入的对象
         */
        returnKeyList(obj) {
            var arr = [];
            for (var i in obj) {
                arr.push(i)
            }
            return arr;
        },
        /**
         * 请求数据渲染
         * @author YS
         * @param {*} sday 查询开始日期
         * @param {*} eday 查询结束日期
         */
        apiAjax(sday, eday) {
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `dstart=${sday}&dend=${eday}` }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body).replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data['res']) === 0) {
                    this.loads();
                    this.tableHead1 = [];
                    this.tableData1 = [];
                    var hed1 = [{ "prop": "0", "label": "角色类型" }, { "prop": "1", "label": "汇总" }];
                    this.tableHead1 = this.tableHead1.concat(hed1, this.getArrJson(this.returnKeyList(data.schoolGameSumData[0].schoolCounts)));
                    for (var i = 0, len = data.schoolGameSumData.length; i < len; i++) {
                        var obj = {}
                        obj[0] = data.schoolGameSumData[i].title;
                        obj[1] = data.schoolGameSumData[i].sum;
                        var lenArr = this.returnValueList(data.schoolGameSumData[i].schoolCounts);
                        for (var j = 0; j < lenArr.length; j++) {
                            obj[j + 2] = lenArr[j]
                        }
                        this.tableData1.push(obj)
                    }
                    this.tableHead2 = [];
                    this.tableData2All = [];
                    console.log(data.schoolGameData)
                    for (var i = 0, len = data.schoolGameData.length; i < len; i++) {
                        var arrhed2 = ["日期", "总活跃"],
                            obj = {};
                        obj["0"] = data.schoolGameData[i].dateStr
                        obj["1"] = data.schoolGameData[i].activeUser
                        var lenArr2 = this.returnValueList(data.schoolGameData[i].activeUserSchoolCounts);
                        console.log(lenArr2)
                        for (var j = 0; j < lenArr2.length; j++) {
                            obj[j + 2] = lenArr2[j]
                        }
                        var lenKeysArr = this.returnKeyList(data.schoolGameData[i].activeUserSchoolCounts);
                        for (var j = 0; j < lenKeysArr.length; j++) {
                            arrhed2 = arrhed2.concat(lenKeysArr[j]);
                        }
                        obj[this.returnKeyList(obj).length] = data.schoolGameData[i].newUser;
                        arrhed2 = arrhed2.concat(["总新增"]);
                        var lenValuesArr = this.returnValueList(data.schoolGameData[i].newUserSchoolCounts);
                        for (var j = 0; j < lenValuesArr.length; j++) {
                            obj[this.returnKeyList(obj).length] = lenValuesArr[j];
                        }
                        var lenKeysArr2 = this.returnKeyList(data.schoolGameData[i].newUserSchoolCounts);
                        for (var j = 0; j < lenKeysArr2.length; j++) {
                            arrhed2 = arrhed2.concat(lenKeysArr2[j])
                        }
                        this.tableData2All.push(obj)
                    }
                    this.tableHead2 = this.getArrJson2(arrhed2);
                    this.page2.dataTotal = this.returnKeyList(this.tableData2All).length;
                    this.tableData2 = this.tableData2All.slice((this.page2.currentPage - 1) * (this.page2.pageSize), this.page2.currentPage * this.page2.pageSize);


                    this.echartsData(data.pieChartList);

                } else {
                    this.errorFun(data['msg'])
                }
            }).catch(function(res) {})
        },
        _init() {
            var arr = ['realTimeData', 'realTimeData2'];
            for (var x = 0; x < arr.length; x++) {
                this[arr[x] + 'Chart'] = echarts.init(document.getElementById(arr[x]));
            }
            window.addEventListener('resize', function() {
                var resizeArr = ['realTimeDataChart', 'realTimeData2Chart']
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        // 获取表数据
        echartsData(d) {
            if (d[0] === undefined) {
                var data = {}
            } else {
                var data = d[0]['jsonStr'];
            }

            var arr = [];
            for (var i = 0; i < data.data[0].length; i++) {
                arr[i] = data.data[0][i][1]
            }
            this.realTimeDataChart.setOption({
                title: {
                    text: d[0].header
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params, ticket, callback) {
                        return params[0].name + ':' + params[0].value
                    }
                },
                xAxis: [{
                        type: 'category',
                        data: data['names']
                    }

                ],
                yAxis: [{
                    type: 'value',
                    splitNumber: data['names'].length,
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        formatter: function(val) {
                            val = val / 1000;
                            return val + 'k'
                        }
                    }
                }],
                series: [{
                    name: data['names'].reverse(),
                    type: 'bar',
                    data: arr.reverse(),
                    barWidth: 10
                }],
                dataZoom: [{
                    start: 0
                }],
                itemStyle: {
                    normal: {
                        color: '#2f7ed8',
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                calculable: true
            });
            if (d[1] === undefined) {
                var data = {}
            } else {
                var data = d[1]['jsonStr'];
            }
            var arr1 = [];
            for (var i = 0; i < data.data[0].length; i++) {
                arr1[i] = data.data[0][i][1]
            }
            this.realTimeData2Chart.setOption({
                title: {
                    text: d[1].header
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params, ticket, callback) {
                        return params[0].name + ':' + params[0].value
                    }
                },

                xAxis: [{
                    type: 'category',
                    data: data['names']
                }],
                yAxis: [{
                    type: 'value',
                    splitNumber: data['names'].length,
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        formatter: function(val) {
                            val = val / 1000;
                            return val + 'k'
                        }
                    }
                }],
                series: [{
                    name: data['names'].reverse(),
                    type: 'bar',
                    data: arr1.reverse(),
                    barWidth: 10
                }],
                dataZoom: [{
                    start: 0
                }],
                itemStyle: {
                    normal: {
                        color: '#2f7ed8',
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                calculable: true
            });
        }
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.DP.uid = localStorage.getItem('ZULONGBIUSERID');
        this.findData(0);
        this._init();

    }
}